package sysmessage

import (
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"os/signal"
	"strings"
	"time"

	"github.com/gorilla/websocket"
)

type MsgItem struct {
	Content  string
	Sender   string
	Receiver string
}

func Connect() {
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	url := "ws://101.35.195.79:8088/ws/admin2?req=ok"
	conn, _, err := websocket.DefaultDialer.Dial(url, nil)
	if err != nil {
		log.Fatal("WebSocket connection error:", err)
	}

	fmt.Println("-------------连接成功-----")
	defer conn.Close()

	// 启动一个 goroutine 来接收消息
	go receiveMessages(conn)

	// 主 goroutine 发送消息
	for {
		select {
		case <-interrupt:
			log.Println("Interrupt signal received, closing connection...")
			err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				log.Println("Failed to send close message:", err)
			}
			select {
			case <-time.After(time.Second):
			}
			return
		case <-time.After(time.Second):

			var msg MsgItem
			msg.Content = "Hello, go gin api Server!"

			msg.Sender = "gin"
			msg.Receiver = "admin"

			xxmsg, _ := json.Marshal(msg)

			err := conn.WriteMessage(websocket.TextMessage, xxmsg)
			// err := conn.WriteMessage(websocket.TextMessage, []byte("Hello, go gin api Server!"))

			if err != nil {
				log.Println("Failed to send message:", err)
				return
			}
		}
	}
}

func receiveMessages(conn *websocket.Conn) {
	for {
		// conn.ReadMessage()
		messageType, message, err := conn.NextReader()
		if err != nil {
			log.Println("Failed to receive message:", err)
			return
		}
		log.Printf("Received message from server: %s\n", message)
		// 判断消息类型
		switch messageType {
		case websocket.TextMessage:
			handleTextMessage(message)
		case websocket.BinaryMessage:
			handleBinaryMessage(message, conn)
		case websocket.CloseMessage:
			return
		}
	}
}

func handleTextMessage(reader io.Reader) {
	messageBytes, err := io.ReadAll(reader)
	if err != nil {
		log.Println("Failed to read text message:", err)
		return
	}
	message := string(messageBytes)
	fmt.Printf("Received text message from client: %s\n", message)
}

func handleBinaryMessage(reader io.Reader, conn *websocket.Conn) {
	gzipReader, err := gzip.NewReader(reader)
	if err != nil {
		log.Println("Failed to create gzip reader:", err)
		return
	}
	defer gzipReader.Close()

	var builder strings.Builder
	io.Copy(&builder, gzipReader)

	// 接收到完整的图片数据后，发送确认消息给客户端
	if err := conn.WriteMessage(websocket.TextMessage, []byte("Received")); err != nil {
		log.Println("Failed to send confirmation message:", err)
	}

	fmt.Println("Received image data from client")
	// 可在这里进行进一步处理，如保存图片到本地等
}

/**

ws://101.35.195.79:8088/ws/admin2?req=ok

{"Content":"Hello, go gin api Server!","Sender":"gin","Receiver":"admin"}

考虑图片数据的压缩、分片发送、接收确认等更复杂的逻辑，以确保图片数据能够稳定、高效地在 WebSocket 上进行传输。

*/
